package com.canplay.screen.utils

import android.os.Handler
import android.os.Looper
import android.view.Gravity
import android.view.LayoutInflater
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.StringRes
import com.canplay.screen.R
import com.canplay.screen.init.appContext


/**
 * @Description: toast工具类
 */
object ToastUtils{
    private var isShowing = false
    fun toast(msg:String,duration:Int = Toast.LENGTH_SHORT){
        if(msg.isEmpty()){
            return
        }
        ThreadUtils.runOnUiThread{
            val toast = Toast(appContext)
            val contentView = LayoutInflater.from(appContext).inflate(R.layout.layout_toast,null)
            val textView = contentView.findViewById<TextView>(R.id.text)
            textView.text = msg
            textView.textAlignment = TextView.TEXT_ALIGNMENT_CENTER
            toast.view = contentView
            toast.setGravity(Gravity.CENTER,0,0)
            toast.duration = duration
            toast.show()

            isShowing = true

            // 使用计时器来跟踪 Toast 的显示时间
            val toastDuration = if (duration == Toast.LENGTH_SHORT) 2000L else 3500L
            Handler(Looper.getMainLooper()).postDelayed({
                isShowing = false
            }, toastDuration)
        }
    }

    fun isToastShowing(): Boolean {
        return isShowing
    }
    fun toast(@StringRes msg:Int,duration: Int = Toast.LENGTH_SHORT){
        toast(appContext.getString(msg),duration)
    }
}
fun String.toast(duration:Int = Toast.LENGTH_SHORT){
    ToastUtils.toast(this, duration)
}
